﻿using System;
using System.Threading.Tasks;
using System.Windows.Input;
using Acr.UserDialogs;
using Cashbook.Services;
using Xamarin.Forms;

namespace Cashbook.ViewModels
{
    public class StatisticsVM: AbstractViewModel
    {
        public ObservableRangeCollection<MonthStaticsVM> MonthStatics { get; set; }
        private BillsDataAccess _billsService;
        public ICommand LoadDataCommand { get; private set; }

		string _title;
		public string Title
		{
			get { return this._title; }
			set
			{
				if (this._title == value)
					return;

				this._title = value;
				this.OnPropertyChanged();
			}
		}

		bool _isBusy;
		public bool IsBusy
		{
			get { return this._isBusy; }
			set
			{
				if (this._isBusy == value)
					return;

				this._isBusy = value;
				this.OnPropertyChanged();
			}
		}


		public StatisticsVM(IUserDialogs dialogs) : base(dialogs)
        {
            Title = "帐单统计";
            _billsService = new BillsDataAccess();
            MonthStatics = new ObservableRangeCollection<MonthStaticsVM>();

            LoadDataCommand = new Command(async () => await ExecuteLoadDataCommand());
        }

        async Task ExecuteLoadDataCommand()
        {
			if (IsBusy)
				return;

			IsBusy = true;

			try
			{
				MonthStatics.Clear();
                var items = await _billsService.GetStatisticsByMonth();
				MonthStatics.ReplaceRange(items);

			}
			catch (Exception ex)
			{
				// Debug.WriteLine(ex);
				await this.Dialogs.AlertAsync("数据加载失败." + ex.Message, "错误", "确定");
			}
			finally
			{
				IsBusy = false;
			}
        }
    }
}
